package com.skymxc.demo.explorer;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.content.PermissionChecker;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.widget.TextView;
import android.widget.Toast;

import com.skymxc.demo.explorer.util.DBUtil;
import com.skymxc.demo.explorer.util.SettingUtil;

public class WelcomeActivity extends AppCompatActivity {

    private TextView tv;
    private boolean isOk;

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String theme = SettingUtil.getTheme(this);
        switch (Integer.parseInt(theme)){
            case 0:
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                break;
            case 1:
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                break;
        }
        setContentView(R.layout.activity_welcome);
        tv = (TextView) findViewById(R.id.text);

//       动画
        AnimationSet set  = new AnimationSet(true);
        set.setDuration(1500);
        set.setInterpolator(new LinearInterpolator());
        RotateAnimation rotate = new RotateAnimation(-180f,0,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
        ScaleAnimation scale = new ScaleAnimation(0,1,0,1, Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0);
        set.addAnimation(rotate);
        set.addAnimation(scale);
        tv.startAnimation(set);

        tv.postDelayed(new Runnable() {
            @Override
            public void run() {
                toMainActivity();
            }
        },1600);

        //初始化数据
        DBUtil.initData();

        //请求权限
        requestPermission();


    }

    /**
     * 请求权限
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestPermission() {

        if (checkVersion()){
            // > 6.0
          int result =-1;
            if (checkTargetSdkVersion()){
                result=checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
            }else{
                result= PermissionChecker.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE);
            }

            //检查权限
            if (result == PermissionChecker.PERMISSION_GRANTED){
                //已经授权
                toMainActivity();
            }else{
                //没有授权
                if (!shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)){
                    new AlertDialog.Builder(this).setTitle("权限说明")
                            .setMessage("此软件是文件管理器 ，必须要文件读取的权限，请在稍后授权")
                            .setNeutralButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},20);
                                }
                            })
                            .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //TODO 退出程序
                                    finish();
                                }
                            })
                            .show();
                }else{
                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},20);
                }

            }
        }else{
            toMainActivity();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 20:
                if (grantResults.length>0 && grantResults[0]== PermissionChecker.PERMISSION_GRANTED){
                    //授权成功
                    toMainActivity();
                }else{
                    //TODO 没有授权 退出
                    Toast.makeText(this,"授权失败，退出程序",Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
        }
    }

    /**
     * 检查 targetSdkVersion 是否 >= 23
     * @return
     */
    private boolean checkTargetSdkVersion(){

        try {
            PackageInfo info= getPackageManager().getPackageInfo(getPackageName(),0);
           if(info.applicationInfo.targetSdkVersion>=Build.VERSION_CODES.M){
               return true;
           }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 检查系统版本是否>= 6.0
     * @return
     */
    private boolean checkVersion(){
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            return true;
        }
        return false;
    }

    private void toMainActivity(){
        if (isOk){
            Intent in = new Intent(WelcomeActivity.this,MainActivity.class);
            startActivity(in);
            finish();
        }else{
            isOk=true;
        }

    }
}
